<template>
  <view class="container">
    <!-- #ifdef MP -->
    <view class="mp-search-box" :class="{ 'sticky-search-box': true }">
      <input class="ser-input" type="text" v-model="searchKeyword" @input="handleInputChange"
             @click="clone()" placeholder="输入关键字搜索" />
      <text class="qu" @click="selSearch(0)">搜索</text>
    </view>
    <!-- #endif -->
    <view class="history-record-section" v-show="!isSearching">
      <text>历史记录</text><text class="delQC" @click="delClear()">清除</text>
      <view class="history-record-list">
        <view class="history-record-item" v-for="(item, index) in searchHisotry"
              :key="index" @click="selSearch(item)">
          <text>{{item.keyword}}</text>
        </view>
      </view>
    </view>

    <view class="tab-bar" v-show="isGoods" :class="{ 'sticky-tab-bar': isGoods }">
      <view class="tab-item" :class="{active: tabIndex === 0}" @click="changeTab(0)">综合</view>
      <view class="tab-item" :class="{active: tabIndex === 1}" @click="changeTab(1)">价格</view>
      <view class="tab-item" :class="{active: tabIndex === 2}" @click="toggleCategories">分类</view>
    </view>

    <view class="category-tags" v-show="showCategories" :class="{ 'sticky-category-tags': showCategories }">
      <view class="category-tag" v-for="(category, index) in categoryList" :key="category.id" @click="selectCategory(category.id)">
        {{category.name}}
      </view>
    </view>

    <view class="guess-section" v-show="isGoods">
      <view
          v-for="(item, index) in searchHisotry" :key="index"
          class="guess-item"
          @click="navToDetailPage(item)"
      >
        <view class="image-wrapper">
          <image :src="item.picUrl" mode="aspectFill"></image>
        </view>
        <text class="title clamp">{{item.name}}</text>
        <text class="price">￥{{item.counterPrice}}</text>
      </view>
    </view>

    <view v-show="isNull">
      暂时还没有这种商品
    </view>
  </view>
</template>

<script>
  import {
    getSearchHistory,
    getSearchGoods,
    getCategory,
    addSearchHistory,
	delSearchHistory
  } from '@/config/api/search.js';
import { mapState } from 'vuex';
  export default {
    data() {
      return {
        searchHisotry: [],
        isSearching: true,
        isGoods: false,
        orderPrice: 0,
        searchKeyword: '', // 新增用于绑定input值的变量
        userId: 0,
        tabIndex: 0,
        categoryList: ['时尚女装', '工艺品'],
        showCategories: false, // 用于控制分类标签是否显示
        searchParameter: {
          name: '',
          categoryId: 0,
          orderPrice: 0,
        },
        isPrice: 0,
        num: 0,
        isNull: false,
      }
    },
    async onLoad() {
      this.selSearchHistory();
    },
	computed: {
	    ...mapState(['userInfo'])
	  },
    methods: {
      async loadData() {

      },
      async selSearchHistory() {
        this.userId = this.userInfo.id;
        try { // 用户搜索历史
          const res = await getSearchHistory({
            userId: this.userId
          })
          if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
            this.searchHisotry = res.data.data
            console.log(this.searchHisotry);
			if (this.searchHisotry.length < 1) {
				this.isSearching = true;
			}
          } else {
            console.error('请求失败:', res?.data?.msg || '未知错误');
          }
        } catch (error) {
          console.error('接口异常:', error)
          this.$message.error('数据加载失败')
        }
      },
      //详情页
      navToDetailPage(item) {
        console.log(item);
        //测试数据没有写id，用title代替
        let id = item.id;
        uni.navigateTo({
          url: `/pages/product/product?id=${id}`
        })
      },
      clone() {
        this.isGoods = false;
        this.showCategories = false;
        this.tabIndex = 0;
        this.searchParameter.categoryId = 0;
        this.isNull = false;
      },
      changeTab(index) {
        this.showCategories = false;
        this.tabIndex = index;
        if (index == 1) {
          this.num += this.tabIndex;
          // 这里可以根据需求添加切换选项卡后的逻辑，比如重新请求不同排序或分类的数据
          if (this.num % 2 == 1) {
            this.isPrice = 1;
          } else {
            this.isPrice = 2;
          }
          this.selSearch('pai');
        } else {
          this.selSearch();
        }

      },
      handleInputChange(e) {
        const value = e.detail.value;
        this.isSearching = value.length > 0;
        if (!value.length) {
          this.isSearching = false;
          this.selSearchHistory();
        }
        this.searchParameter.name = value; // 实时更新searchParameter的name
		
		if (this.userInfo.id == null) {
			this.isSearching = true;
		}
      },
      async selSearch(item) {
        try {
		  if (item == 0) {
			  this.tabIndex = 0;
			  this.searchParameter.categoryId = 0;
		  }
          if (item && item != 'pai') {
            this.searchKeyword = item.keyword; // 点击历史记录时，取历史记录关键词
          }
          if (item != 'pai') {
            this.isPrice = 0;
          }
          this.searchParameter.orderPrice = this.isPrice;
          this.searchParameter.name = this.searchKeyword;
          // if (this.searchParameter.name == '' || this.searchParameter.name == null) {
          //   uni.showToast({
          //     title: '请输入搜索内容',
          //     icon: 'none',
          //     duration: 2000
          //   });
          //   return;
          // }

          this.isSearching = true;
          // 若选择了分类，更新searchParameter.categoryId
          if (this.selectedCategory) {
            // 假设selectedCategory存储选中分类的ID，需在selectCategory方法中处理赋值
            this.searchParameter.categoryId = this.selectedCategory.id;
          }
		  
		  if (this.searchParameter.categoryId == null) {
			  this.searchParameter.categoryId = 0;
		  }
          const res = await getSearchGoods(
            {name: this.searchKeyword,
			orderBy: this.searchParameter.orderPrice,
			categoryId: this.searchParameter.categoryId}
          )
		  console.log(this.searchKeyword + " " + this.searchParameter.orderPrice + " " + this.searchParameter.categoryId);
          if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
            200) {
            this.searchHisotry = res.data.data
            console.log(this.searchHisotry);
            this.isGoods = this.searchHisotry.length > 0;
            if (!this.isGoods) {
              this.isNull = true;
            }
          } else {
            console.error('请求失败:', res?.data?.msg || '未知错误');
          }
          this.selCategory(this.searchParameter.name);
          this.insertSearchHistroy({name: this.searchParameter.name});
        } catch (error) {
          console.error('接口异常:', error)
          this.$message.error('数据加载失败')
        }
      },
      selectCategory(categoryId) {
        this.searchParameter.orderPrice = 0;
        this.searchParameter.categoryId = categoryId;
        this.selSearch();
        this.showCategories = false;
      },
      toggleCategories() {
        this.showCategories =!this.showCategories;
		this.tabIndex = 2;
      },
      async selCategory(name) {
        try {
          const res = await getCategory(
            {name:name}
          )
          if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
            200) {
            this.categoryList = res.data.data
            console.log(this.categoryList);
          } else {
            console.error('请求失败:', res1?.data?.msg || '未知错误');
          }
        } catch (error) {
          console.error('接口异常:', error)
          this.$message.error('数据加载失败')
        }

      },
      async insertSearchHistroy(item) {
        try {
          const res = await addSearchHistory(
            {userId: this.userId, keyword: item.name}
          )
          if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
            200) {

          } else {
            console.error('请求失败:', res1?.data?.msg || '未知错误');
          }
        } catch (error) {
          console.error('接口异常:', error)
          this.$message.error('数据加载失败')
        }
      },
	  async delClear(){
		  try {
		    const res = await delSearchHistory(
		      {userId: this.userId}
		    )
		    if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
		      200) {
				this.selSearchHistory();
		    } else {
		      console.error('请求失败:', res1?.data?.msg || '未知错误');
		    }
		  } catch (error) {
		    console.error('接口异常:', error)
		    this.$message.error('数据加载失败')
		  }
	  },
    }
  }
</script>

<style lang="scss">
  page {
    height: 100%;
    background-color: #F4F4F4;
  }
  /* #ifdef MP */
 .mp-search-box {
	margin-top: -1px;
    height: 40px;
    width: 100%;
    padding: 0 20upx;
    border-top: solid #D9D9D9 1px;
    border-bottom: solid #D9D9D9 1px;
    background-color: #fff;
    position: relative;
   .ser-input {
      position: relative;
      top: 5px;
      width: 320px;
      height: 56upx;
      line-height: 56upx;
      font-size: 28upx;
      color: $font-color-base;
      border-radius: 5px;
      background-color: #F4F4F4;
      padding-left: 1em;
    }

   .qu {
      position: relative;
      left: 335px;
      top: -20px;
    }
  }

 .sticky-search-box {
    position: sticky;
	top: 0;
    z-index: 2; /* 确保在其他元素之上 */
  }

  /* #endif */
 .history-record-section {
    padding: 10rpx;
    background-color: #fff;
  }

 .history-record-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 5px;
  }

 .history-record-item {
    background-color: #fff;
    /* 设置记录项背景为白色 */
    border: 1px solid #e0e0e0;
    /* 添加边框 */
    padding: 5rpx 10rpx;
    margin-right: 10rpx;
    margin-bottom: 10rpx;
  }

 .delQC {
    float: right;
    /* 让清除按钮靠右 */
    color: #999;
    /* 设置颜色 */
    margin-right: 10rpx;
    /* 调整右边距 */
  }
 .guess-section {
    display: flex;
    flex-wrap: wrap;
    padding: 0 30upx;
    background: #fff;
    margin-top: 5px;
   .guess-item {
      display: flex;
      flex-direction: column;
      width: 48%;
      padding-bottom: 40upx;
      &:nth-child(2n + 1) {
        margin-right: 4%;
      }
    }
   .image-wrapper {
      width: 100%;
      height: 330upx;
      border-radius: 3px;
      overflow: hidden;
      image {
        width: 100%;
        height: 100%;
        opacity: 1;
      }
    }
   .title {
      font-size: $font-lg;
      color: $font-color-dark;
      line-height: 80upx;
    }
   .price {
      font-size: $font-lg;
      color: $uni-color-primary;
      line-height: 1;
    }
  }
 .tab-bar {
    display: flex;
    justify-content: space-around;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;
    z-index: 1;
  }
 .sticky-tab-bar {
    position: sticky;
    top: 40px; /* 假设搜索框高度为 40px，根据实际情况调整 */
  }
 .tab-item {
    padding: 10rpx 20rpx;
    font-size: 30upx;
    color: #333;
    cursor: pointer;
    transition: color 0.3s ease;
  }
 .tab-item.active {
    color: #f40;
    border-bottom: 2px solid #f40;
  }
 .category-tags {
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    padding: 10rpx;
    z-index: 1;
  }
 .sticky-category-tags {
    position: sticky;
    top: 73px; /* 假设搜索框和 tab-bar 总高度为 80px，根据实际情况调整 */
  }
 .category-tag {
    border: 1px #000 solid;
    border-radius: 5px;
    padding: 5rpx 10rpx;
    margin: 15px;
    cursor: pointer;
  }
</style>